@Library('jenkins-shared-lib') _ 

pipeline {
    agent {label 'agent01'}
        // 设置全局选项
    options {
        // 构建超时时间设置为 1 小时
        timeout(time: 1, unit: 'HOURS')
        // 保持最近 10 次构建记录
        buildDiscarder(logRotator(numToKeepStr: '10'))
        // 禁用并发构建
        disableConcurrentBuilds()
    }

    stages {
        stage('Checkout') {
            steps {
                echo "============ 开始构建${env.DEPLOY_APP} ============"
                showAppEnv()
                script {
                    def gitArgs = [
                        branch: env.BRANCH,
                        url: env.APP_GIT_URL
                    ]

                    // 仅在 CREDENTIAL_ID 非空且非空白时传
                    if (env.CREDENTIAL_ID?.trim()) {
                        gitArgs.credentialsId = env.CREDENTIAL_ID
                    }

                    git(gitArgs)
                }
            }
        }

        stage('Build with Docker') {
            steps {
                script {
                    docker.image('docker.1ms.run/node:20').inside {
                            sh '''
                            npm install pnpm -g
                            pnpm config set registry https://registry.npmmirror.com
                            pnpm install
                            ${BUILD_CMD}
                            '''
                        }
                }
            }
        }
        stage('Ansible playbook'){
            steps {
                deploy(
                    deploy_host: "${env.DEPLOY_HOST}",
                    artifact: "${WORKSPACE}/${env.BUILD_ARTIFACT}",
                    deploy_app: "${env.DEPLOY_APP}",
                    tags: "${env.DEPLOY_TAGS}"
                )
            }
        }
    }
}